package com.future.lock.me.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.future.baselib.activity.BaseActivity;
import com.future.baselib.adapter.FragmentAdapter;
import com.future.baselib.view.CustomViewCenterDialog;
import com.future.lock.R;
import com.future.lock.common.Constants;
import com.future.lock.common.MyApp;
import com.future.lock.common.RefreshDataUtils;
import com.future.lock.common.http.HttpUtils;
import com.future.lock.common.http.response.DefaultHttpResponse;
import com.future.lock.me.adapter.GateWayAdapter;
import com.future.lock.me.adapter.LockAdapter;
import com.future.lock.me.fragment.RecyclerFragment;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MachineManagerActivity extends BaseActivity implements ViewPager.OnPageChangeListener {

    @BindView(R.id.iv_left)
    ImageView ivLeft;
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.view_line)
    View viewLine;
    @BindView(R.id.layout_title)
    FrameLayout layoutTitle;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.layout_tab_1_bottom)
    View layoutTab1Bottom;
    @BindView(R.id.layout_tab_2_bottom)
    View layoutTab2Bottom;
    @BindView(R.id.tv_tab_1)
    TextView tvTab1;
    @BindView(R.id.tv_tab_2)
    TextView tvTab2;

    int color_648ddd = Color.parseColor("#648ddd");
    int color_333 = Color.parseColor("#333333");

    private FragmentAdapter adapter;
    String[] titles = {"网关", "智能锁"};
    private ArrayList<Fragment> fragments;
    private CustomViewCenterDialog deleteDialog;
    private int currentPosition;
    private GateWayAdapter gateWayAdapter;
    private LockAdapter lockAdapter;

    @Override
    protected void initContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_machine_manager);
        ButterKnife.bind(this);
    }

    @Override
    protected void initView() {
        setTitle("设备管理");
        fragments = new ArrayList<>();
        initFragmentsAdapter();
        adapter = new FragmentAdapter(getSupportFragmentManager(), fragments);
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(this);
    }

    private void initFragmentsAdapter() {
        RecyclerFragment fragment1 = new RecyclerFragment();
        gateWayAdapter = new GateWayAdapter(R.layout.item_gateway, null);
        gateWayAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            currentPosition = position;
            showDeleteDialog();
        });
        fragment1.setAdapter(gateWayAdapter);
        fragments.add(fragment1);
        RefreshDataUtils.refreshGatewayList(MachineManagerActivity.this, refresh -> {gateWayAdapter.setNewData(Constants.gatewayList);});



        RecyclerFragment fragment2 = new RecyclerFragment();
        lockAdapter = new LockAdapter(R.layout.item_lock, Constants.lockList);
        lockAdapter.setOnItemClickListener((adapter, view, position) -> {
            Bundle bundle = new Bundle();
            bundle.putInt("position",position);
            currentPosition = position;
            startActivityForResult(MachineDetailManagerActivity.class,bundle,0x321);
        });
        fragment2.setAdapter(lockAdapter);
        fragments.add(fragment2);
    }

    private void showDeleteDialog() {
        if (deleteDialog == null) {
            View rootView = LayoutInflater.from(this).inflate(R.layout.dialog_default, null);
            ((TextView) rootView.findViewById(R.id.tv_message)).setText(R.string.delete_gateway_tip);
            rootView.findViewById(R.id.btn_cancel).setOnClickListener(v -> {
                if (deleteDialog != null) {
                    deleteDialog.dismiss();
                }
            });
            Button btnOk = (Button) rootView.findViewById(R.id.btn_ok);
            btnOk.setText("确定");
            btnOk.setOnClickListener(v -> {
                deleteDialog.dismiss();
                HttpUtils.getHttpApi()
                        .delGateway(MyApp.getUserToken(), gateWayAdapter.getData().get(currentPosition).gatewayId)
                        .enqueue(new Callback<String>() {
                            @Override
                            public void onResponse(Call<String> call, Response<String> response) {
                                DefaultHttpResponse httpResponse = new DefaultHttpResponse();
                                httpResponse.parse(response.body());
                                if (httpResponse.success == 1) {
                                    gateWayAdapter.remove(currentPosition);
                                    RefreshDataUtils.refreshLockList(MachineManagerActivity.this, new RefreshDataUtils.RefreshCallback() {
                                        @Override
                                        public void refreshResult(boolean refresh) {
                                            if (refresh) {
                                                lockAdapter.setNewData(Constants.lockList);
                                            }
                                        }
                                    });
                                } else {
                                    if (httpResponse.code == 112){
                                        RefreshDataUtils.logout(mContext);
                                    }
                                    toast(httpResponse.msg);
                                }
                            }

                            @Override
                            public void onFailure(Call<String> call, Throwable t) {
                                toast(t.getMessage());
                            }
                        });
            });
            deleteDialog = new CustomViewCenterDialog(this)
                    .setView(rootView)
                    .builder();
        }
        deleteDialog.show();
    }

    @Override
    protected void initLogic() {

    }

    @Override
    protected void getBundleExtras(Bundle extras) {

    }

    @OnClick({R.id.layout_tab_1, R.id.layout_tab_2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_tab_1:
                viewPager.setCurrentItem(0);
                break;
            case R.id.layout_tab_2:
                viewPager.setCurrentItem(1);
                break;
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        if (position == 0) {
            tvTab1.setTextColor(color_648ddd);
            tvTab2.setTextColor(color_333);
            layoutTab1Bottom.setVisibility(View.VISIBLE);
            layoutTab2Bottom.setVisibility(View.GONE);
        } else {
            tvTab1.setTextColor(color_333);
            tvTab2.setTextColor(color_648ddd);
            layoutTab1Bottom.setVisibility(View.GONE);
            layoutTab2Bottom.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == resultCode && requestCode == 0x321) {
            lockAdapter.remove(currentPosition);
        }
        if (resultCode == 0x322) {
            lockAdapter.setNewData(Constants.lockList);
        }
    }
}
